package com.tgit.sso.core.conf;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tgit.sso.core.common.ResponseT;

/**
 * 配置的key值-字符串常亮池
 * @author 范再军
 * 2018年9月12日
 */
public class SsoConf {
	
    public static final Logger LOGGER=LoggerFactory.getLogger(SsoConf.class);
    
	//对于客户端重定向的key值
    public static final String REDIRECT_URL = "redirect_url";
	//对于客户端重定向的服务
    public static final String SERVICE = "service";

    //cookie中k-v的k值
    public static final String SSO_SESSIONID = "tgit-sso-sessionid";
    public static final String SSO_SESSIONID_LOCALE = "tgit-sso-locale";
    //cookie中k-v的k值
    public static final String SSO_CONFIGURATION = "tgit-sso-configuration";

    //token模式中k-v的k值,header中不支持下划线模式
    public static final String SSO_TOKEN= "tgit-sso-token";
    
    //登录sso的账号的key值
    public static final String SSO_USER = "sso_account";

    //sso服务地址的key值
    public static final String SSO_SERVER = "sso_server";

    //登录的上下文路径
    public static final String SSO_LOGIN = "/login";
   
    //用户注册
    public static final String RE_USER = "/reuser";
    //忘记密码
    public static final String RE_PWD = "/repwd";
    //服务协议
    public static final String RE_AGREEMENT = "/agreement";

    //登出的上下文
    public static final String SSO_LOGOUT = "/logout";
    
    //登录动作
    public static final String SSO_DO_LOGIN = "/doLogin";
    //注册动作
    public static final String DO_RE_USER = "/doReuser";
    //发送至邮箱
    public static final String DO_SEND_EMAIL = "/sendEmail";
    //忘记密码动作
    public static final String DO_RE_PWD = "/doRepwd";


    //登出的路径-过滤器会用到
    public static final String SSO_LOGOUT_PATH = "logout_path";
    
    //客户端地址，配置目的，代理可能出问题
    public static final String CLIENT_SERVER = "client_server";
    
    //redis配置地址
    public static final String REDIS_ADDRESS = "redis_address";
    
    //redis配置密码
    public static final String REDIS_PASSWORD = "redis_password";
    
    //sso-server判断通断地址-私有云部署内网配置地址 
    public static final String SSO_CONNECT_URL = "sso_connect_url";
    
    //是否走单点登录地址 ssoFlag="sso"走单点登录，不配置为null就是不走sso
    public static final String SSO_FLAG = "sso_flag";

    //客户端地址，配置目的，代理可能出问题
    public static final String LOGO_CLASS = "logo_class";

    //定义一个登录报错的预想值
    public static final ResponseT<String> SSO_LOGIN_FAIL_RESULT = new ResponseT<String>(500, "该用户没有登录");
    
    //错误信息提示
    public static class ERROR_SSO{
    	public static final String DB_CONNECT_MSG="数据库初始化失败";
    	public static final String TOKEN_ERROR_MSG = "token过期或无效";
    }
    public static final String LOGOUT_SUCCESS = "LOGOUT SUCCESS!";
    
    public static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json;charset=UTF-8";

    //session timeout 取值范围
    public static final Integer SESSION_TIMEOUT_RANGE1 = 3600;
    public static final Integer SESSION_TIMEOUT_RANGE2 = 86400;

    public static final String SESSION_TIMEOUT = "session_timeout";
    public static final String IMAX_URL = "imax_url";

    public static final String COMMA_SEPARATOR = ",";

    //ip白名单
    public static  String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //可能出现有多个ip地址的情况
        if (StringUtils.isNotBlank(ip)) {
            String[] ipArr = ip.split(",");
            if (ipArr.length > 1) {
                ip = ipArr[0];
            }
        }
        ip = ip.equals("0:0:0:0:0:0:0:1")?"192.168.0.23":ip;
        return ip;
    }
    //表单验证错误码
    public static enum ERRORCODE{
    	USERNAME,PASSWORD,USERNAME_PASSWORD,VALID_CODE,VALID_CODE_ERROR,IP_LIMIT
    }
    //正则表达式
    public static class PATTERN{
    	public static final String URL="^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\\\/])+(\\\\?{0,1}(([A-Za-z0-9-~]+\\\\={0,1})([A-Za-z0-9-~]*)\\\\&{0,1})*)$";
    }

    
    //url校验
    public static boolean validUrl(String url) {
    	Pattern pattern = Pattern.compile(SsoConf.PATTERN.URL);
    	if (pattern.matcher(url).matches()) {
    		return true;
    	}
    	return false;
    }
    //传入需要连接的IP，返回是否连接成功
    public static boolean isReachableIp(String remoteInetAddr) {
    	boolean reachable = false; 
    	 try {   
    		 InetAddress address = InetAddress.getByName(remoteInetAddr); 
             reachable = address.isReachable(100);  
         } catch (Exception e) {  
            e.printStackTrace();  
         }  
        return reachable;
    }
    //传入url字符串
    public static boolean isReachableUrl(String urlStr) {
    	URL url = null;
    	try {   
    		url = new URL(urlStr);
    		@SuppressWarnings("unused")
			InputStream in = url.openStream();
    		return true;
    	} catch (IOException  e) {  
    		LOGGER.info(url+"status: connect error");
    		return false;
    	}  
    }
}
